local skynet = require "skynet"
local netpack = require "netpack"
local socket = require "socket"
local cjson = require "cjson"
local protocol = require "protocol"

local CMD = {}

local client_fd

local protocolInstance = tonumber(...)

local function send_client(protocol_id, v)
	socket.write(client_fd, netpack.pack(cjson.encode{protocol_id, v}))
end

skynet.register_protocol {
	name = "client",
	id = skynet.PTYPE_CLIENT,
	unpack = function(msg, sz)
		local str = skynet.tostring(msg, sz)
		local jsonStr = cjson.decode(str)
		return jsonStr
	end,
	dispatch = function(_, _, data)
		print("receive message:",data, data[2])
		print("Protoinstance:", protocolInstance)
		local realData = cjson.decode(data[2])
		skynet.call(protocolInstance, "lua", "on_packet", tonumber(data[1]), realData, skynet.self())
	end
}

function CMD.start(gate, fd)
	client_fd = fd
	skynet.call(gate, "lua", "forward", fd)
	send_client (protocol.id.pid_login_test, {param1 = 6, param2 = "isstr", param3 = "2014-8-8 12:12:12", param4 = "432543252344325"})
end

CMD.send_data = send_client

skynet.start(function()
	skynet.dispatch("lua", function(_, _, command, ...)
		local f = CMD[command]
		skynet.ret(skynet.pack(f(...)))
	end)
end)
